package com.chagee.store.operation.server.event.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chagee.store.operation.common.constant.SupplierWorkOrderConstant;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.server.entity.WorkOrderReceiverDO;
import com.chagee.store.operation.server.event.dao.WorkOrderReceiverMapper;
import com.chagee.store.operation.server.model.param.GetCompanyStoreParam;
import com.chagee.store.operation.server.model.param.SupplierWorkOrderQueryParam;
import com.chagee.store.operation.server.model.vo.CompanyStorePageVO;
import com.chagee.store.operation.server.model.vo.CompanyVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName WorkOrderReceiverBaseService  //类名称
 * @Description: //类描述
 * @Author: Jacky-zhan	//作者
 * @CreateDate: 2024/04/25 14:10	//创建时间
 * @UpdateUser: Jacky-zhan	//作者
 * @UpdateDate: 2024/04/25 14:10	//更新时间
 * @UpdateRemark: 更新的信息
 * @Version: 1.0    //版本号
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkOrderReceiverBaseService extends ServiceImpl<WorkOrderReceiverMapper, WorkOrderReceiverDO> {

	@Resource
	private WorkOrderReceiverMapper workOrderReceiverMapper;

	/**
	 * 分页列表
	 *
	 * @param supplierWorkOrderQueryParam 查询条件
	 * @param page                        分页条件
	 * @return 分页数据
	 */
	public Page<WorkOrderReceiverDO> queryWorkOrderByBaseParam(SupplierWorkOrderQueryParam supplierWorkOrderQueryParam, Page<WorkOrderReceiverDO> page) {
		//选择 分公司(companyId='0000' or companyId='1111') 时，将子公司id置空查询，
		if (SupplierWorkOrderConstant.COMPANY_ID_0000.equals(supplierWorkOrderQueryParam.getCompanyId())
			|| SupplierWorkOrderConstant.COMPANY_ID_1111.equals(supplierWorkOrderQueryParam.getCompanyId())) {
			supplierWorkOrderQueryParam.setCompanyId("");
		}
		//查询全部数据
		if (StringUtils.isNotBlank(supplierWorkOrderQueryParam.getDocumentStatus())
			&& SupplierWorkOrderConstant.DOCUMENT_STATUS_ALL.equals(supplierWorkOrderQueryParam.getDocumentStatus())) {
			supplierWorkOrderQueryParam.setDocumentStatus("");
		}
		/*LambdaQueryChainWrapper<WorkOrderReceiverDO> workOrderDOLambdaQueryChainWrapper = lambdaQuery();
		workOrderDOLambdaQueryChainWrapper
			.in(CollectionUtils.isNotEmpty(supplierWorkOrderQueryParam.getStoreCode()), WorkOrderReceiverDO::getStoreCode, supplierWorkOrderQueryParam.getStoreCode())
			.like(StringUtils.isNotBlank(supplierWorkOrderQueryParam.getStoreName()), WorkOrderReceiverDO::getStoreName, supplierWorkOrderQueryParam.getStoreName())
			.eq(StringUtils.isNotBlank(supplierWorkOrderQueryParam.getDocumentStatus()), WorkOrderReceiverDO::getDocumentStatus, supplierWorkOrderQueryParam.getDocumentStatus())
			.le(StringUtils.isNotBlank(supplierWorkOrderQueryParam.getEndCreateTime()), WorkOrderReceiverDO::getCreateTime, supplierWorkOrderQueryParam.getEndCreateTime())
			.ge(StringUtils.isNotBlank(supplierWorkOrderQueryParam.getStartCreateTime()), WorkOrderReceiverDO::getCreateTime, supplierWorkOrderQueryParam.getStartCreateTime())
			.eq(StringUtils.isNotBlank(supplierWorkOrderQueryParam.getCompanyId()), WorkOrderReceiverDO::getCompanyId, supplierWorkOrderQueryParam.getCompanyId())
			.eq(WorkOrderReceiverDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);*/
		//登录人账号类型是主账户，根据指定字段进行分组
		/*if (Objects.nonNull(supplierWorkOrderQueryParam.getUserType()) && 1 == supplierWorkOrderQueryParam.getUserType()) {
			workOrderDOLambdaQueryChainWrapper
				.eq(Objects.nonNull(supplierWorkOrderQueryParam.getSupplierId()), WorkOrderReceiverDO::getSupplierId, supplierWorkOrderQueryParam.getSupplierId())
				.groupBy(WorkOrderReceiverDO::getWorkOrderNumber);
		}
		if (Objects.nonNull(supplierWorkOrderQueryParam.getUserType()) && 2 == supplierWorkOrderQueryParam.getUserType()) {
			workOrderDOLambdaQueryChainWrapper
				.eq(Objects.nonNull(supplierWorkOrderQueryParam.getReceiverID()), WorkOrderReceiverDO::getReceiverId, supplierWorkOrderQueryParam.getReceiverID());
		}
		workOrderDOLambdaQueryChainWrapper
			.orderByDesc(WorkOrderReceiverDO::getCreateTime);
		return workOrderReceiverMapper.selectPage(page, workOrderDOLambdaQueryChainWrapper.getWrapper());*/
		Page<WorkOrderReceiverDO> workOrderReceiverDOPage = new Page<>();
		//根据用户类型判断查询sql
		if (SupplierWorkOrderConstant.USER_TYPE_MAIN_ACCOUNT.equals(String.valueOf(supplierWorkOrderQueryParam.getUserType()))) {
			//门店编码查询根据状态allStoreStatus判断，1：全部门店
			if (StringUtils.isNotBlank(supplierWorkOrderQueryParam.getAllStoreStatus())
				&& SupplierWorkOrderConstant.ALL_STORE_STATUS.equals(supplierWorkOrderQueryParam.getAllStoreStatus())) {
				//查询所有的门店编码并赋值
				GetCompanyStoreParam getCompanyStoreParam = new GetCompanyStoreParam();
				getCompanyStoreParam.setCompanyId(supplierWorkOrderQueryParam.getCompanyId());
				getCompanyStoreParam.setSupplierId(supplierWorkOrderQueryParam.getSupplierId());
				List<CompanyStorePageVO> companyStorePageVOS = workOrderReceiverMapper.selectListByParam(getCompanyStoreParam);
				List<String> storeCode = companyStorePageVOS.stream().map(CompanyStorePageVO::getStoreCode).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(storeCode)) {
					supplierWorkOrderQueryParam.setStoreCode(storeCode);
				}
			}
			//主账户查询
			workOrderReceiverDOPage = workOrderReceiverMapper.selectPageList(supplierWorkOrderQueryParam, page);
		}
		if (SupplierWorkOrderConstant.USER_TYPE_SUB_ACCOUNTS.equals(String.valueOf(supplierWorkOrderQueryParam.getUserType()))) {
			//门店编码查询根据状态allStoreStatus判断，1：全部门店
			if (StringUtils.isNotBlank(supplierWorkOrderQueryParam.getAllStoreStatus())
				&& SupplierWorkOrderConstant.ALL_STORE_STATUS.equals(supplierWorkOrderQueryParam.getAllStoreStatus())) {
				//查询所有的门店编码并赋值
				GetCompanyStoreParam getCompanyStoreParam = new GetCompanyStoreParam();
				getCompanyStoreParam.setCompanyId(supplierWorkOrderQueryParam.getCompanyId());
				getCompanyStoreParam.setReceiverID(supplierWorkOrderQueryParam.getReceiverID());
				List<CompanyStorePageVO> companyStorePageVOS = workOrderReceiverMapper.selectListByParam(getCompanyStoreParam);
				List<String> storeCode = companyStorePageVOS.stream().map(CompanyStorePageVO::getStoreCode).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(storeCode)) {
					supplierWorkOrderQueryParam.setStoreCode(storeCode);
				}
			}
			//子账户查询
			workOrderReceiverDOPage = workOrderReceiverMapper.selectPageList2(supplierWorkOrderQueryParam, page);
		}
		return workOrderReceiverDOPage;
	}

	/**
	 * 根据门店编号查询接单人信息
	 *
	 * @param storeCode 门店编号
	 * @return 接单人信息
	 */
	public List<WorkOrderReceiverDO> getAllByStoreCode(String storeCode) {
		return workOrderReceiverMapper.getAllByStoreCode(storeCode);
	}

	/**
	 * 插入数据
	 *
	 * @param workOrderReceiverDO DO对象
	 */
	public void insert(WorkOrderReceiverDO workOrderReceiverDO) {
		workOrderReceiverMapper.insert(workOrderReceiverDO);
	}

	/**
	 * 根据接单人id+门店编号+工单编号+状态:not in(4,5) 混合查询接单人信息
	 *
	 * @param receiverId      接单人id
	 * @param storeCode       门店编号
	 * @param workOrderNumber 工单编号
	 * @return list
	 */
	public List<WorkOrderReceiverDO> getByFix(Long receiverId, String storeCode, String workOrderNumber) {
		return workOrderReceiverMapper.getByFix(receiverId, storeCode, workOrderNumber);
	}

	/**
	 * 根据供应商id查询所有接过单的company信息（需去重）
	 *
	 * @param supplierId 供应商id
	 * @return list
	 */
	public List<CompanyVO> getBySupplierId(Long supplierId) {
		return workOrderReceiverMapper.selectListBySupplierId(supplierId);
	}

	/**
	 * 根据接单人id查询所有接过单的company信息（需去重）
	 *
	 * @param receiverID 接单人id
	 * @return list
	 */
	public List<CompanyVO> getByReceiverID(Long receiverID) {
		return workOrderReceiverMapper.selectListByReceiverID(receiverID);
	}

	/**
	 * 分页列表
	 *
	 * @param getCompanyStoreParam 查询条件
	 * @param page                 分页条件
	 * @return 分页数据
	 */
	public Page<CompanyStorePageVO> getCompanyStoreList(GetCompanyStoreParam getCompanyStoreParam, Page<WorkOrderReceiverDO> page) {
		if (Objects.isNull(getCompanyStoreParam)) {
			//入参为空
			throw new BizException(BizErrorCode.PARAMETER_IS_NULL);
		}
		return workOrderReceiverMapper.selectPageByParam(getCompanyStoreParam, page);
	}

	/**
	 * 根据工单编号+待执行状态查询
	 *
	 * @param workOrderNumber 工单编号
	 * @return 工单信息
	 */
	public List<WorkOrderReceiverDO> selectListByWorkOrderNumber(String workOrderNumber) {
		return workOrderReceiverMapper.selectListByWorkOrderNumber(workOrderNumber);
	}

	/**
	 * 根据工单id+待执行状态查询
	 *
	 * @param workOrderId 工单id
	 * @return 工单信息
	 */
	public List<WorkOrderReceiverDO> selectListByWorkOrderId(Long workOrderId) {
		return workOrderReceiverMapper.selectListByWorkOrderId(workOrderId);
	}

	/**
	 * 通过工单编号查询接单人信息
	 *
	 * @param workOrderNumber 工单编号
	 * @return 接单人信息
	 */
	public List<WorkOrderReceiverDO> getAllByWorkOrderNumber(String workOrderNumber) {
		return workOrderReceiverMapper.getAllByWorkOrderNumber(workOrderNumber);
	}

	/**
	 * 根据工单id查询
	 *
	 * @param workOrderId 工单id
	 * @return 工单信息
	 */
	public List<WorkOrderReceiverDO> selectListByOrderId(Long workOrderId) {
		return workOrderReceiverMapper.selectListByOrderId(workOrderId);
	}

	public List<WorkOrderReceiverDO> queryOrderByWorkOrderNumber(String workOrderNumber) {
		LambdaQueryWrapper<WorkOrderReceiverDO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(WorkOrderReceiverDO::getWorkOrderNumber, workOrderNumber)
			.eq(WorkOrderReceiverDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		List<WorkOrderReceiverDO> workOrderReceiverDOList = workOrderReceiverMapper.selectList(wrapper);
		return workOrderReceiverDOList;
	}

	public void batchUpdateOrderStatus(List<WorkOrderReceiverDO> list, Integer documentStatus, String documentScore) {
		list.stream().forEach(s -> {
			updateOrderStatus(s, documentStatus, documentScore);
		});
	}

	public Boolean updateOrderStatus(WorkOrderReceiverDO workOrderReceiverDO, Integer documentStatus, String documentScore) {
		return this.update(
			lambdaUpdate().eq(WorkOrderReceiverDO::getId, workOrderReceiverDO.getId())
				.set(ObjectUtil.isNotEmpty(documentStatus), WorkOrderReceiverDO::getDocumentStatus, documentStatus)
				.set(StringUtils.isNotBlank(documentScore), WorkOrderReceiverDO::getDocumentScore, documentScore)
				.set(WorkOrderReceiverDO::getUpdateTime, new Date()).getWrapper());
	}

}
